package com.starblink.search.result.ui.fragment.store

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMLazyLoadingFragment
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.common.databinding.CellSearchStoreBinding
import com.starblink.android.common.view.store.SearchStoreRecommendModel
import com.starblink.android.common.view.store.StoreRecommendResultCell
import com.starblink.android.common.view.store.StoreResultCell
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.route.RoutePage
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.search.R
import com.starblink.search.config.SearchConfig
import com.starblink.search.databinding.FgmSearchStoreResultBinding
import com.starblink.search.result.ui.cell.GoodsEmptyCell
import com.starblink.search.result.ui.cell.GoodsTitleCell
import com.starblink.search.result.ui.fragment.BaseSearchFragment

class StoreResultFragment :
    BaseSearchFragment<FgmSearchStoreResultBinding, StoreResultVM>() {

    val adapter by lazyOnNone {
        MutableAdapter(viewModel.contentList).apply {
            addVhDelegate {
                StoreResultCell(
                    CellSearchStoreBinding.inflate(
                        layoutInflater,
                        it,
                        false
                    ),
                    searchTerm = viewModel.contentSearch,
                    searchType = searchType,
                    pageDef = SpmPageDef.SearchStoresPage,
                ) { merchant, position ->
                    CommonMutateManage.subscribeOrNotMerchant(
                        requireContext(),
                        merchant.id,
                        merchant.merchantName,
                        merchant.subOrNot,
                        resultCallback = {
                            if (it) {
                                ApolloValSetExt.setApolloVal<MerchantWebVOF>(
                                    merchant, "subOrNot",
                                    !merchant.subOrNot
                                )

                                ApolloValSetExt.setApolloVal<MerchantWebVOF>(
                                    merchant, "subNum",
                                    if (merchant.subOrNot) merchant.subNum + 1 else merchant.subNum - 1
                                )
                                refreshItem(position)
                            }
                        })
                }
            }
            addVhDelegate {
                StoreRecommendResultCell(
                    pageDef = SpmPageDef.SearchStoresPage,
                    searchTerm = viewModel.contentSearch,
                    searchType = searchType,
                    viewGroup = it
                ) { merchant, position ->
                    CommonMutateManage.subscribeOrNotMerchant(
                        requireContext(),
                        merchant.id,
                        merchant.merchantName,
                        merchant.subOrNot,
                        resultCallback = {
                            if (it) {
                                ApolloValSetExt.setApolloVal<MerchantWebVOF>(
                                    merchant, "subOrNot",
                                    !merchant.subOrNot
                                )

                                ApolloValSetExt.setApolloVal<MerchantWebVOF>(
                                    merchant, "subNum",
                                    if (merchant.subOrNot) merchant.subNum + 1 else merchant.subNum - 1
                                )
                                refreshItem(position)
                            }
                        })
                }
            }
            addVhDelegate {
                GoodsEmptyCell(it)
            }
            addVhDelegate {
                GoodsTitleCell(it)
            }
        }
    }

    override fun emptyMessage(): String = string(R.string.search_store_empty_tip)

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FgmSearchStoreResultBinding = FgmSearchStoreResultBinding.inflate(inflater)


    override fun startObserve() {

        viewModel.contentLD.observe(this) {
            adapter.refreshAll()

            if (it) {
                viewBinding.refresher.finishLoadMore()
            } else {
                viewBinding.refresher.finishLoadMoreWithNoMoreData()
            }
        }
    }

    override fun initData() {
        viewModel.contentSearch = arguments?.getString(QUERY_WORD, "") ?: ""
    }

    var searchType: String = ""

    override fun initView(view: View) {
        searchType =
            if (viewModel.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_HOT) "trendingWord" else if (viewModel.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_SHADING) "shadingWord" else "normal"

        viewBinding.recycler.layoutManager = LinearLayoutManager(requireContext())
        viewBinding.recycler.adapter = adapter

        viewBinding.refresher.setOnLoadMoreListener {
            if (viewModel.contentHasResult) {
                viewModel.pageNo++
                viewModel.loadData()
            } else {
                viewModel.recPageNo++
                viewModel.loadRecStore()
            }
        }
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            if (event.id != null) {
//                viewModel.contentList.indexOfFirst { it is MerchantWebVOF && event.id == it.id }
//                    .takeIf { it > -1 }?.let {
//                        (viewModel.contentList[it] as? MerchantWebVOF?)?.apolloValue(
//                            "subOrNot",
//                            event.followed
//                        )
//                        adapter.notifyItemChanged(it)
//                    }
                viewModel.contentList.indexOfFirst { it is MerchantWebVOF && event.id == it.id }
                    .takeIf { it > -1 }?.let {
                        var brand: MerchantWebVOF = viewModel.contentList[it] as MerchantWebVOF
                        changeBrandItem(brand, event, it)
                    }
                viewModel.contentList.indexOfFirst { it is SearchStoreRecommendModel && event.id == it.merchant.id }
                    .takeIf { it > -1 }?.let {
                        var brand: MerchantWebVOF = (viewModel.contentList[it] as SearchStoreRecommendModel).merchant
                        changeBrandItem(brand, event, it)
                    }
            }
        }
    }

    private fun changeBrandItem(
        brand: MerchantWebVOF,
        event: FollowStoreEvent,
        it: Int
    ) {
        brand.apolloValue(
            "subOrNot",
            event.followed
        )
//        brand.apolloValue(
//            "subNum",
//            if (brand.subOrNot) (brand.subNum + 1) else (brand.subNum - 1)
//        )
        adapter.notifyItemChanged(it)
    }

    override fun initLoad() {

    }

    override fun onLazyInitData() {
        super.onLazyInitData()
        viewModel.loadData()
    }

    private fun refreshItem(position: Int) {
        adapter.notifyItemChanged(position)
    }


    companion object {

        const val QUERY_WORD = "query_word"
        private const val KEY_SEARCH_SCENE = "search_word_scene"

        fun newInstance(
            queryWord: String,
            searchScene: Int = 0
        ) = StoreResultFragment().apply {
            arguments = bundleOf(
                QUERY_WORD to queryWord,
                KEY_SEARCH_SCENE to searchScene,
            )
        }

    }

    override fun spmPageId(): Int = SpmPageDef.SearchStoresPage

    override fun onResume() {
        super.onResume()
        if (arguments?.getInt(KEY_SEARCH_SCENE) == RoutePage.Search.SCENE.STORES.value) {
            pageExposure(
                SpmPageDef.SearchStoresPage,
                mapOf(
                    "searchTerm" to viewModel.contentSearch,
//                    "shadingWord" to "",
//                    "trending" to if (viewModel.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_HOT ||
//                        viewModel.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_SHADING
//                    ) viewModel.contentSearch else "",
                    "searchType" to if (viewModel.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_HOT) "trendingWord" else if (viewModel.searchWordSource == SearchConfig.SearchWordSourceConfig.O_TYPE_SHADING) "shadingWord" else "normal",
                )
            )
        }
    }
}